/**
 ******************************************************************************
 * @file           : ring_buffer.h
 * @brief          : Ring Buffer Header File
 ******************************************************************************
 * @attention
 *
 * 环形缓冲区（FIFO）
 * 线程安全、无锁实现
 *
 ******************************************************************************
 */

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __RING_BUFFER_H
#define __RING_BUFFER_H

#ifdef __cplusplus
extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include <stdint.h>
#include <stdbool.h>

/* Exported types ------------------------------------------------------------*/

/**
 * @brief 环形缓冲区结构体
 */
typedef struct
{
    uint8_t *buffer;        /*!< 缓冲区指针 */
    uint32_t size;          /*!< 缓冲区大小 */
    volatile uint32_t head; /*!< 写指针 */
    volatile uint32_t tail; /*!< 读指针 */
    volatile uint32_t count;/*!< 数据个数 */
} RingBuffer_t;

/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported variables --------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/

/* 初始化和复位 */
void ring_buffer_init(RingBuffer_t *rb, uint8_t *buffer, uint32_t size);
void ring_buffer_reset(RingBuffer_t *rb);

/* 写入数据 */
bool ring_buffer_put(RingBuffer_t *rb, uint8_t data);
uint32_t ring_buffer_write(RingBuffer_t *rb, const uint8_t *data, uint32_t len);

/* 读取数据 */
bool ring_buffer_get(RingBuffer_t *rb, uint8_t *data);
uint32_t ring_buffer_read(RingBuffer_t *rb, uint8_t *data, uint32_t len);

/* 查看数据（不移除） */
bool ring_buffer_peek(RingBuffer_t *rb, uint8_t *data);
uint32_t ring_buffer_peek_at(RingBuffer_t *rb, uint32_t offset, uint8_t *data);

/* 状态查询 */
bool ring_buffer_is_empty(RingBuffer_t *rb);
bool ring_buffer_is_full(RingBuffer_t *rb);
uint32_t ring_buffer_available(RingBuffer_t *rb);
uint32_t ring_buffer_free_space(RingBuffer_t *rb);

/* 查找和搜索 */
int32_t ring_buffer_find(RingBuffer_t *rb, uint8_t data);
int32_t ring_buffer_find_string(RingBuffer_t *rb, const char *str);

#ifdef __cplusplus
}
#endif

#endif /* __RING_BUFFER_H */
